package com.huizluo.module4.chatroom;

import java.io.*;
import java.util.HashMap;
import java.util.Set;

public class Room extends Thread{

    private HashMap<Integer,User> userMap = new HashMap<>();

    void addUser(User user){
        this.userMap.put(user.getId(),user);
        String s = "user [" + user.getId() + "] 加入房间";
        Message msg = new Message(0, s.getBytes());
        msg.setUserID(user.getId());
        this.SendMsgToAll(user,msg);
    }

    void SendMsgToAll(User currUser,Message msg) {
        Set<Integer> set = userMap.keySet();
        for (Integer id : set){
            User user = userMap.get(id);
            if (user.getId().compareTo(currUser.getId())!=0){
                System.out.println("send to "+ user.getId());
                ObjectOutputStream oop = null;
                try {
                    oop = new ObjectOutputStream(user.getConn().getOutputStream());
                    oop.writeObject(msg);
                    oop.flush();
                } catch (IOException e) {
                    this.userMap.remove(currUser.getId());
                    System.out.println(e.getMessage());
                }
            }
        }
    }

    void SendFileName(User currUser,String name){
        Set<Integer> set = userMap.keySet();
        for (Integer id : set){
            User user = userMap.get(id);
            if (user.getId() != currUser.getId()){
                DataOutputStream dos = null;
                try {
                    dos = new DataOutputStream(user.getConn().getOutputStream());
                    dos.writeUTF(name);
                    dos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    void SendFileLength(User currUser,long len){
        Set<Integer> set = userMap.keySet();
        for (Integer id : set){
            User user = userMap.get(id);
            if (user.getId() != currUser.getId()){
                DataOutputStream dos = null;
                try {
                    dos = new DataOutputStream(user.getConn().getOutputStream());
                    dos.writeLong(len);
                    dos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    void SendFileToAll(User currUser,byte[] bytes,int len){
        Set<Integer> set = userMap.keySet();
        for (Integer id : set){
            User user = userMap.get(id);
            if (user.getId() != currUser.getId()){
                DataOutputStream dos = null;
                try {
                    dos = new DataOutputStream(user.getConn().getOutputStream());
                    dos.write(bytes,0,len);
                    dos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}
